define(['config', 'text!app/module/system/employee.html', 'laypage',
    'mydialog', 'autocomplete', 'jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
    mydialog, autocomplete, jqGrid, common, laydate) {

    var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_url = "/api/employee/list";

    var model = avalon.define({
        $id: "employee",
        employeeInfo: {},
        // 查询条件
        query: {
            name: "",
        },
        userInfo: {
            id: "",
            userName: "",
            password: "",
            employeeId: "",
        },
        statusArr: [],
        userArr: [],
        selected: [],
        roles: [],
        arr: [{
            key: "男",
            val: "0"
        }, {
            key: "女",
            val: "1"
        }],

        init: function () {
            model.loadGrid();
            model.addEvent();
        },
        loadGrid: function () {
            function t(val, opt, row) {
                var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="javascript:void();" ms-click="edit(el)"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
                return html_con;
            }

            var i = Public.setGrid();
            $("#grid").jqGrid({
                loadBeforeSend: function (jqXHR) {
                    jqXHR.setRequestHeader("X-AuthToken", token);
                },
                datatype: "json",
                mtype: "POST",
                url: grid_url,
                postData: model.query.$model,
                loadComplete: function (data) {},
                loadError: function (xhr, status, error) {
                    alert(JSON.parse(xhr.responseText).msg);
                },
                colModel: [{
                        name: "operating",
                        label: "操作",
                        width: '5%',
                        formatter: t,
                    },
                    {
                        name: "id",
                        label: "编号",
                        width: '4%',
                    },
                    {
                        name: "name",
                        label: "员工姓名",
                        width: '6%',
                    },
                    {
                        name: "gender",
                        label: "性别",
                        width: '5%',
                        formatter: function (value, options, rowData) {
                            if (value === 0) {
                                return '男';
                            } else {
                                return '女';
                            }
                        }
                    },
                    {
                        name: "telNo",
                        label: "电话",
                        width: '10%',
                    },
                    {
                        name: "departName",
                        label: "所属机构",
                        width: '12%',
                        /* formatter: function (value, options, rowData) {
                            //value   判断是否为undefined  防止ajax重复发送  造成死循环
                            if (typeof (value) == "undefined") {
                                $.ajax({
                                    type: "POST",
                                    url: "/api/employee/getOrgName?id=" + rowData.id,
                                    beforeSend: function (xhr) {
                                        xhr.setRequestHeader("X-AuthToken", token);
                                    },
                                    success: function (data, status, xhr) {
                                        if (data.org_name == "") {
                                            $("#grid").setCell(options.rowId, "org_name", null);
                                            $("#grid").setCell(options.rowId, "orgId", null);
                                        } else {
                                            $("#grid").setCell(options.rowId, "org_name", data.org_name);
                                            $("#grid").setCell(options.rowId, "orgId", data.orgId);
                                        }

                                    },
                                    error: function (responseData, textStatus, errorThrown) {
                                        // alert("无效的所属机构");
                                    }
                                });
                            }
                            return value;
                        } */
                    },
                    {
                        name: "departMemoTX",
                        hidden: true
                    },
                    {
                        name: "departID",
                        hidden: true
                    },
                    {
                        name: "userId",
                        hidden: true
                    },
                    {
                        name: "originalUserId",
                        hidden: true
                    },
                    {
                        name: "username",
                        label: "关联用户",
                        width: "5%"
                    },
                    {
                        name: "create_TM",
                        label: "创建时间",
                        width: '10%',
                        formatter: Public.custDatefmter
                    },
                    {
                        name: "manage",
                        label: "账号管理",
                        width: '13%',
                        formatter: function (val, opt, row) {
                            if (!row.userId) {
                                return "无";
                            }
                            return '<div data-id="' + row.id + '"><a class="userManage" href="javascript:void(0)"><span>编辑账号</span></a>' +
                                ' <a class="userRole" href="javascript:void(0)"><span>设置角色</span></a>' +
                                ' <a class="resetPwd" href="javascript:void(0)"><span>重置密码</span></a></div>';
                        },
                    }
                ],
                cmTemplate: {
                    sortable: false,
                    title: false,
                    align: "center"
                },
                page: 1,
                rowNum: 10,
                rowList: [10, 20, 30],
                height: i.h,
                autowidth: true,
                pager: '#page',
                sortname: 'id',
                viewrecords: true,
                forceFit: false,
                rownumbers: true,
                multiselect: true,
                multiboxonly: true,
                sortorder: "desc",
                jsonReader: {
                    root: "data.list",
                    records: "data.totalRow",
                    total: "data.totalPage",
                    repeatitems: false,
                    id: "id"
                },
                loadError: function () {
                    parent.Public.tips({
                        type: 1,
                        content: "加载数据异常！"
                    })
                }
            })
        },
        reset: function () {
            model.query = {
                name: ""
            };
            model.queryData();
        },
        queryData: function () {
            debugger;
            $("#grid").jqGrid("setGridParam", {
                url: grid_url,
                datatype: "json",
                mtype: 'POST',
                page:1,
                postData: model.query.$model
            }).trigger("reloadGrid");
        },
        //添加或更新
        edit: function (employeeInfo) {
            if (employeeInfo === -1) {
                // 创建用户
                model.initEmployee();
                model.arr = [{
                    key: "男",
                    val: "0"
                }, {
                    key: "女",
                    val: "1"
                }];
                url = "/api/employee/save";
            } else {
                // 修改用户
                model.employeeInfo = employeeInfo;
                if (model.employeeInfo.gender == "男") {
                    model.employeeInfo.gender = "0";
                    model.arr = [{
                        key: "男",
                        val: "0"
                    }, {
                        key: "女",
                        val: "1"
                    }];
                } else {
                    model.employeeInfo.gender = "1";
                    model.arr = [{
                        key: "男",
                        val: "0"
                    }, {
                        key: "女",
                        val: "1"
                    }];
                }
                url = "/api/employee/save";

            }

 //           getAllUsers();

//            $("#employeeOrgName").autocomplete({
//                serviceUrl: "/api/depart/get",
//                paramName: "name",
//                // 其他ajax配置
//                ajaxSettings: {
//                    beforeSend: function (xhr) {
//                        xhr.setRequestHeader("X-AuthToken", token);
//                    },
//                },
//                showNoSuggestionNotice: true,
//                noSuggestionNotice: '无匹配项',
//                onSearchStart: function (query) {
//                    // if (model.depart.parentID != "") {
//                    //     model.depart.parentID = "";
//                    // }
//                },
//                transformResult: function (response) {
//                    var obj = $.parseJSON(response);
//                    return {
//                        suggestions: $.map(obj.data, function (data) {
//                            return {
//                                value: data.memo_TX,
//                                data: data.departID
//                            };
//                        })
//                    };
//                },
//                onSelect: function (suggestion) {
//                    model.employeeInfo.departID = suggestion.data;
//                },
//                onSearchComplete: function (query, suggestions) {
//                    $("div[data-index=0]").addClass("autocomplete-selected");
//                }
//            });
            // 弹出层
            dialog({
                title: '编辑用户信息',
                content: $('#editUser'),
                okValue: "确定",
                ok: function () {
                    // 提交修改
                    model.employeeInfo.create_TM = new Date(model.employeeInfo.create_TM);
               //     if (model.employeeInfo.orgId != "") {
                        $.ajax({
                            type: "POST",
                            url: url,
                            contentType: "application/json",
                            data: JSON.stringify(model.employeeInfo.$model),
                            beforeSend: function (xhr) {
                                xhr.setRequestHeader("X-AuthToken", token);
                            },
                            success: function (data, status, xhr) {
                                model.queryData();
                            },
                            error: function (responseData, textStatus, errorThrown) {
                                alert("系统异常");
                            }
                        });
               //     }
                },
                cancelValue: "取消",
                cancel: function () {}
            }).showModal();


        },
        editUser: function (id) {
            //编辑账号 弹出层
            var title = "";
            if (id == -1) {
                model.initUser();
                title = "新增账号信息";
            } else {
                title = "编辑账号信息";
                getUser(id);
            }
            model.statusArr = [{
                "val": "true",
                "text": "有效"
            }, {
                "val": "false",
                "text": "无效"
            }]

            dialog({
                title: title,
                content: $('#editUserInfo'),
                okValue: "确定",
                ok: function () {
                    $.ajax({
                        type: "POST",
                        url: "/api/user/save",
                        dataType: 'json',
                        contentType: "application/json",
                        data: JSON.stringify(model.userInfo),
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("X-AuthToken", token);
                        },
                        success: function (data, status, xhr) {
                            if (data.success) {
                                dialog({
                                    title: "提示",
                                    content: "操作成功",
                                    okValue: "确定",
                                    ok: function () {}
                                }).showModal();
                                if (id == -1) {
                                    getAllUsers();
                                }
                            }
                        },
                        error: function (responseData, textStatus, errorThrown) {}

                    });
                },
                cancelValue: "取消",
                cancel: function () {

                }
            }).showModal();

        },
        editUserRole: function (id) {
            //编辑账号 弹出层
            model.selected = [];
            $.ajax({
                type: "GET",
                url: "/api/employee/userInfo?id=" + id,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("X-AuthToken", token);
                },
                success: function (data, status, xhr) {
                    var title = "";
                    if (data.success) {
                        title = "编辑账号信息";
                        model.userInfo = data.data.sysUser;
                        $.each(data.data.sysUser.roles, function (index, element) {
                            model.selected.push(element.id.toString());
                        })

                    } else {
                        //false 没有用户信息  新建
                        title = "新建账号信息";
                    }
                    model.roles = data.data.sysRoleList;
                    // model.userInfo.employeeId = id;
                    debugger;

                    dialog({
                        title: title,
                        content: $('#editUserRole'),
                        okValue: "确定",
                        ok: function () {
                            var roles = new Array();
                            debugger;
                            $.each(data.data.sysRoleList, function (i, val) {
                                if (model.selected.$model.indexOf(val.id.toString()) != -1) {
                                    roles.push(val);
                                }
                            })
                            model.userInfo.roles = roles;
                            $.ajax({
                                type: "POST",
                                url: "/api/user/save?roleIds=" + model.selected,
                                dataType: 'json',
                                contentType: "application/json",
                                data: JSON.stringify(model.userInfo),
                                beforeSend: function (xhr) {
                                    xhr.setRequestHeader("X-AuthToken", token);
                                },
                                success: function (data, status, xhr) {
                                    if (data.success) {
                                        dialog({
                                            title: "提示",
                                            content: "操作成功",
                                            okValue: "确定",
                                            ok: function () {}
                                        }).showModal();
                                    }
                                },
                                error: function (responseData, textStatus, errorThrown) {}

                            });
                        },
                        cancelValue: "取消",
                        cancel: function () {

                        }
                    }).showModal();
                },
                error: function (responseData, textStatus, errorThrown) {}

            });

        },
        del: function (ids) {
            dialog({
                title: "确认操作",
                content: "确定删除？ 此操作不可恢复！",
                okValue: "确定",
                ok: function () {

                    $.ajax({
                        type: "POST",
                        url: "/api/employee/delEmployee",
                        data: {
                            "ids": ids
                        },
                        beforeSend: function (xhr) {
                            xhr.setRequestHeader("X-AuthToken", token);
                        },
                        success: function (data, status, xhr) {
                            if (data) {
                                $('#grid').jqGrid('delRowData', ids);
                            }
                            model.queryData();
                        },
                        error: function (responseData, textStatus, errorThrown) {
                            alert("Failed: " + responseData);
                        }

                    });

                },
                cancelValue: "取消",
                cancel: function () {}
            }).showModal();
        },
        resetPwd: function (id) {
            var func = function (data) {
                if (data.success) {
                    var d = dialog({
                        content: "操作成功",
                    }).showModal();
                    setTimeout(
                        function () {
                            d.close().remove();
                        }, 1500)

                }

            }
            Public.ajaxGet("/api/user/resetPwd", {
                "id": id
            }, token, func);
        },
        addEvent: function () {
            var t = this;
            $(".grid-wrap").on("click", ".fa-edit", function (e) {
                var t = $(this).parent().data("id");
                model.edit($("#grid").getRowData(t));
            });
            // 删除
            $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
                var ei = [];
                var e = $(this).parent().data("id");
                ei.push(e);
                model.del(e);
            });
            $("#search").click(function (e) {
                e.preventDefault();
                model.queryData();
            });
            $(".fa-refresh").click(function (e) {
                e.preventDefault();
                model.reset();
                model.queryData();
            })
            //编辑用户信息
            $(".grid-wrap").on("click", ".userManage", function (e) {
                var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                    userId = $("#grid").jqGrid("getRowData", id).userId;
                model.editUser(userId);
            })
            $(".grid-wrap").on("click", ".userRole", function (e) {
                var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                    userId = $("#grid").jqGrid("getRowData", id).userId;
                model.editUserRole(userId);
            })
            $(".grid-wrap").on("click", ".resetPwd", function (e) {
                var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                    userId = $("#grid").jqGrid("getRowData", id).userId;
                dialog({
                    title: "提示",
                    content: "此操作将使用户恢复为默认密码。",
                    okValue: "确定",
                    ok: function () {
                        model.resetPwd(userId);
                    },
                    cancel: function () {},
                    cancelValue: "取消"
                }).showModal();

            })
//            $("#aadddd").click(function (t) {
//                model.edit(-1);
//            });
            $("#btn-batchDel").click(function (e) {
                e.preventDefault();
                // if (Business.verifyRight("BU_DELETE")) {
                var t = $("#grid").jqGrid("getGridParam", "selarrrow");
                t.length ? model.del(t.join()) : parent.Public.tips({
                    type: 2,
                    content: "请选择需要删除的项"
                })
                // }
            });
            // 设置用户角色
        },
        initEmployee: function () {
            model.employeeInfo = {
                id: "",
                name: "",
                gender: "0",
                empNo: "",
                telNo: "",
                appUser_CD: "",
                tel2_TX: "",
                create_TM: "",
                sysUser_YN: "",
                implement_NR: "",
                professional_NR: "",
//                userId: "",
//                originalUserId: "",
//                username: "",
//                departID: "",
//                departMemoTX: "",
//                departName: "",
            }
        },
        initUser: function () {
            model.userInfo = {
                id: "",
                userName: "",
                password: "",
                email: "",
                status: "true",
                employeeId: "",
            }
        }
    });

    function getUser(id) {
        $.ajax({
            type: "GET",
            url: "/api/user/get/" + id,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("X-AuthToken", token);
            },
            success: function (data, status, xhr) {
                if (data.success) {
                    model.userInfo = data.data[0];
                } else {
                    dialog({
                        title: "操作异常",
                        content: "数据获取失败",
                        okValue: "确定",
                        ok: function () {}
                    }).showModal();
                }
            },
            error: function (responseData, textStatus, errorThrown) {}

        });
    }

    function getAllUsers() {
        var func = function (data) {
            model.userArr = data;
        }
        Public.ajaxGet("/api/user/getUsers", {}, token, func)
    }


    require(['jquery', 'domReady!'], function ($) {});

    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {} // 切换菜单时销毁原来的view
    };
    return viewmod;
});